package cn.rumoss.nettyinaction.echo;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 客户端需要做的事情：
 * (1)连接服务器
 * (2)发送信息
 * (3)发送的每个信息，等待和接收从服务器返回的同样的信息
 * (4)关闭连接
 * @author HeCG
 *
 */
public class EchoClient {

	private final String host;
	private final int port;
	
	public EchoClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void start() throws Exception {
		
		EventLoopGroup group = new NioEventLoopGroup();
		
		try {
			Bootstrap clientBootstrap = new Bootstrap();
			clientBootstrap.group(group)// 指定 EventLoopGroup 来处理客户端事件。由于我们使用 NIO 传输，所以用到了NioEventLoopGroup 的实现
				.channel(NioSocketChannel.class)// 使用的 channel 类型是一个用于 NIO 传输
				.remoteAddress(new InetSocketAddress(host, port))// 设置服务器的 InetSocketAddress
				.handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline()// 当建立一个连接和一个新的通道时，创建添加到 EchoClientHandler 实例 到 channel pipeline
								.addLast(new EchoClientHandler());
						}

					});
			ChannelFuture future = clientBootstrap.connect().sync();
			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}
		
	}

	public static void main(String[] args) throws Exception {

		if(args.length!=2) {
			System.err.println("Usage: " + EchoClient.class.getSimpleName() + " <host> <port>");
			return;
		}
		
		String host = args[0];
		int port = Integer.parseInt(args[1]);
		
		new EchoClient(host, port).start();

	}

}
